Create function to get Nth highest salary #1
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
PR Title Format: 176.NthHighestSalary.cpp
Intuition
The problem asks to find the Nth highest salary from the Employee table. A direct approach is to use SQL concepts like ORDER BY with LIMIT and OFFSET, but in LeetCode-style C++ SQL implementation, we use a subquery to skip the top (N-1) distinct salaries and then select the next highest.
The key idea is:
Sort distinct salaries in descending order.
Skip the first (N-1) salaries.
Return the next one.
Approach
We use an SQL query wrapped in a C++ function:
The inner query selects all distinct salaries in descending order.
The LIMIT 1 OFFSET N-1 ensures we fetch the Nth highest.
If N is greater than the number of distinct salaries, we return NULL.
In LeetCode’s context, the function must return a query string.
Code Solution (C++)
// 176.NthHighestSalary.cpp
class Solution {
public:
string nthHighestSalary(int N) {
return "SELECT DISTINCT Salary FROM Employee ORDER BY Salary DESC LIMIT 1 OFFSET " + to_string(N - 1);
}
};
Related Issues
Closes SjxSubham#176
By submitting this PR, I confirm that:
This is my original work not totally AI generated
I have tested the solution thoroughly on LeetCode
I have maintained proper PR description format
This is a meaningful contribution, not spam